﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authentication;
using System.Security.Claims;
using System.Net;
using Polaris.Domain.Model.Constant;
using Newtonsoft.Json;

namespace Polaris.Common.FilterAttribute
{
    /// <summary>
    /// 自定义权限控制类
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = false)]
    public class CustomAuthorizeAttribute : Attribute, IAuthorizationFilter
    {
        /// <summary>
        /// 角色类型
        /// </summary>
        public string Role { get; set; } = RoleConstant.User;

        /// <summary>
        /// 是否需要进行权限验证
        /// </summary>
        public bool IsAuthorize { get; set; } = true;


        /// <summary>
        /// 重写基类的验证方式，加入自定义的Ticket验证
        /// </summary>
        /// <param name="actionContext"></param>
        public async void OnAuthorization(AuthorizationFilterContext context)
        {
            Console.WriteLine(DateTime.Now.ToString() + Role + "---" + IsAuthorize);
            if (IsAuthorize)
            {
                var token = await context.HttpContext.GetTokenAsync("access_token");
                if (token == null)
                {
                    // 如果没有权限，返回 401
                    //var result = new ContentResult
                    //{
                    //    StatusCode = (int)HttpStatusCode.Unauthorized,
                    //    Content = "未获得授权"
                    //};
                    context.Result = new UnauthorizedResult();
                    return;
                }
                var tokenHandler = new JwtSecurityTokenHandler();
                var key = Encoding.UTF8.GetBytes(AppConfig.GetConfigInfo("JwtTokenOptions:SecurityKey"));
                var principal = tokenHandler.ValidateToken(token, new TokenValidationParameters
                {
                    ValidateIssuer = true,
                    ValidIssuer = AppConfig.GetConfigInfo("JwtTokenOptions:Issuer"),
                    ValidateAudience = true,
                    ValidAudience = AppConfig.GetConfigInfo("JwtTokenOptions:Audience"),
                    IssuerSigningKey = new SymmetricSecurityKey(key),
                    ValidateLifetime = true
                }, out SecurityToken validatedToken);

                var jwtToken = (JwtSecurityToken)validatedToken;
                var claims = jwtToken.Claims;
                var roleClaim = claims.Where(c => c.Type == ClaimTypes.Role);
                var roleList = roleClaim.Select(d => d.Value.ToLower()).ToList();
                //如果接口被所有角色访问，不需要判断权限
                if (Role.ToLower() != RoleConstant.All)
                {
                    if (!roleList.Contains(Role.ToLower()))
                    {
                        //用户权限角色没有包含接口权限角色，没有接口权限返回401
                        context.Result = new ForbidResult();
                        //var result = new ContentResult
                        //{
                        //    StatusCode = (int)HttpStatusCode.Forbidden,
                        //    Content = "权限不足，无法访问"
                        //};
                        //context.Result = result;
                        return;
                    }
                }
                //var userData = principal.FindFirst(ClaimTypes.UserData)?.Value;
                //var tokenModel = JsonConvert.DeserializeObject<TokenModel>(userData);
            }

            
            //var token = context.HttpContext.Request.Headers["Authorization"].FirstOrDefault()?.Split(" ").Last();
        }
    }
    public class TokenModel
    {
        public string UserId { get; set; }

        public List<string> UserMenuList { get; set; }
    }
}
